//
//  LoginViewController.swift
//  你的AI
//
//  Created by 丸子 on 2024/6/3.
//

import UIKit
import AuthenticationServices
import YYText
class LoginViewController: BaseViewController {
    let disposeBag = DisposeBag()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    private lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_video_back"), for: .normal)
        button.setClosureTouchUpInside_k { [weak self] in
            self?.dismiss(animated: true)
        }
        return button
    }()
    
    var countdownTimer: Timer?
      var remainingSeconds = 60
    let viewModel = LoginViewModel()
    
    func fastState(isopen:Bool) {
        phoneFieldView.isHidden = isopen
        codeView.isHidden = isopen
        agreeBtn.isHidden = isopen
        loginBtn.isHidden = isopen
        fastLoginView.isHidden = !isopen
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        view.addSubviews([headerIV, backView, backBtn])
        backView.addSubviews([phoneFieldView, codeView, agreeBtn, textLabel, loginBtn, otherLine, otherTipsLb, appleBtn])
        backView.addSubview(fastLoginView)
        fastState(isopen: false)
        headerIV.snp.makeConstraints { make in
            make.top.trailing.equalToSuperview()
            make.leading.equalToSuperview().offset(-1)
            make.height.equalTo(GET_WIDTH(W: 288))
        }
        
        backBtn.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop).offset(10)
            make.leading.equalToSuperview().offset(14)
            make.width.height.equalTo(24)
        }
        
        backView.snp.makeConstraints { make in
            make.top.equalTo(headerIV.snp.bottom).offset(-44)
            make.leading.trailing.equalToSuperview().inset(14)
            make.bottom.equalToSuperview()
        }
        
        phoneFieldView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(14)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(55)
        }
        
        codeView.snp.makeConstraints { make in
            make.top.equalTo(phoneFieldView.snp.bottom).offset(0)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(55)
        }
        
        agreeBtn.snp.makeConstraints { make in
            make.top.equalTo(codeView.snp.bottom).offset(30)
            make.leading.equalToSuperview().offset(44)
            make.height.equalTo(24)
        }
        
        textLabel.snp.makeConstraints { make in
            make.centerY.equalTo(agreeBtn)
            make.leading.equalTo(agreeBtn.snp.trailing).offset(6)
            make.trailing.equalToSuperview().offset(-20)
        }
        
        loginBtn.snp.makeConstraints { make in
            make.top.equalTo(agreeBtn.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(34)
            make.height.equalTo(44)
        }
        
//        phoneBtn.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.bottom.equalTo(self.safeBottom).offset(-75)
//            make.height.equalTo(44)
//            make.width.equalTo(0)
//        }
        
        appleBtn.snp.makeConstraints { make in
//            make.centerY.equalTo(phoneBtn)
//            make.trailing.equalTo(phoneBtn.snp.leading).offset(-36)
//            make.width.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(self.safeBottom).offset(-75)
            make.height.equalTo(44)
            make.width.equalTo(44)
        }
        
//        aBtn.snp.makeConstraints { make in
//            make.centerY.equalTo(phoneBtn)
//            make.leading.equalTo(phoneBtn.snp.trailing).offset(36)
//            make.width.height.equalTo(44)
//        }
        
        otherTipsLb.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(appleBtn.snp.top).offset(-12)
            make.height.equalTo(20)
        }
        
        otherLine.snp.makeConstraints { make in
            make.centerY.equalTo(otherTipsLb)
            make.height.equalTo(1)
            make.leading.trailing.equalToSuperview().inset(36)
        }
        
        fastLoginView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.bottom.equalTo(otherTipsLb.snp.top)
        }
        
        bindEvent()
        
        GlobalRx.loginSuccessSubject.observe(on: MainScheduler.instance).subscribe(onNext: {[weak self] model in
            XLog.d("登录", "登录成功")
            self?.dismiss(animated: true)
        }).disposed(by: disposeBag)
    }
    
    func bindEvent(){
        agreeBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.agreeBtn.isSelected = !self.agreeBtn.isSelected
        }
        
        codeView.codeBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self, let phone = self.phoneFieldView.phoneNumberTextField.text else { return }
            if !phone.isChinesePhoneNumber() {
                NDProgressHUD.showError(title: "提示", subtitle: "请输入正确的手机号")
                return
            }
            kHideKeyboard()
            if !agreeBtn.isSelected {
                let view = UserAGView()
                Appearance.addViewToWindow(view)
                view.chooseDone = { [weak self] in
                    self?.agreeBtn.isSelected = true
                }
                return
            }
            self.viewModel.getCode(loginType: 1, phone: phone)
            startCountdown()
        }
        
        loginBtn.setClosureTouchUpInside_k { [weak self] in
            self?.phoneLogin()
        }
        
        appleBtn.setClosureTouchUpInside_k { [weak self] in
            if #available(iOS 13.0, *) {
                self?.appleLogin()
            } else {
                NDProgressHUD.show(message: "你的设备不支持苹果登录")
            }
        }
        
        aBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            if !agreeBtn.isSelected {
                NDProgressHUD.showError(title: "提示", subtitle: "请同意用户协议和隐私政策")
                return
            }
            self.viewModel.deviceLogin()
        }
    }
    
    func openXy(){
        if let url = URL(string: "\(apiHost)/api/text/contract") {
            // 使用 UIApplication 打开 URL
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    func phoneLogin() {
        if !agreeBtn.isSelected {
            NDProgressHUD.showError(title: "提示", subtitle: "请同意用户协议和隐私政策")
            return
        }
        guard let phone = self.phoneFieldView.phoneNumberTextField.text else { return }
        if !phone.isChinesePhoneNumber() {
            NDProgressHUD.showError(title: "提示", subtitle: "请输入正确的手机号")
            return
        }
        guard let code = self.codeView.phoneNumberTextField.text else { return }
        if code.count <= 0 {
            NDProgressHUD.showError(title: "提示", subtitle: "请输入正确的验证码")
            return
        }
        self.viewModel.login(loginType: 1, phone: phone, code: code)
    }
    
    lazy var headerIV: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_login_header")
        return imageView
    }()
    
    lazy var backView: UIView = {
        let view = UIView()
        view.corners([.layerMinXMinYCorner, .layerMaxXMinYCorner], cornerRadius: 10)
        view.backgroundColor = .white
        return view
    }()
    
    lazy var phoneFieldView: LoginInputView = {
        let view = LoginInputView()
        view.iconIV.image = UIImage(named: "icon_login_phone")
        return view
    }()
    
    lazy var codeView: LoginInputView = {
        let view = LoginInputView()
        view.iconIV.image = UIImage(named: "icon_login_safe")
        view.codeBtn.isHidden = false
        view.phoneNumberTextField.placeholder = "请输入验证码"
        return view
    }()
    
    lazy var agreeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_ag_nor"), for: .normal)
        button.setImage(UIImage(named: "icon_login_ag"), for: .selected)
        return button
    }()
    
    // 懒加载创建 UITextView
    lazy var textLabel: YYLabel = {
        let label = YYLabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        // 创建富文本字符串
        let fullText = "我已阅读并同意《用户协议》《隐私政策》"
        let attributedString = NSMutableAttributedString(string: fullText)
        // 设置通用字体属性
        let fullRange = NSRange(location: 0, length: attributedString.length)
        attributedString.addAttributes([
            .font: UIFont.pingFangSCRegular(ofSize: 12), // 替换成你需要的字体
            .foregroundColor: Theme.color.text_d2 // 替换成你需要的颜色
        ], range: fullRange)
        // 设置《用户协议》的链接和颜色
        let userAgreementRange = (fullText as NSString).range(of: "《用户协议》")
        attributedString.yy_setTextHighlight(userAgreementRange, color: UIColor(hexString: "#45FFFF"), backgroundColor: nil) { _, _, _, _ in
            if let url = URL(string: "\(apiHost)/api/text/contract") {
                UIApplication.shared.open(url)
            }
        }
        // 设置《隐私政策》的链接和颜色
        let privacyPolicyRange = (fullText as NSString).range(of: "《隐私政策》")
        attributedString.yy_setTextHighlight(privacyPolicyRange, color: UIColor(hexString: "#45FFFF"), backgroundColor: nil) { _, _, _, _ in
            if let url = URL(string: "\(apiHost)/api/text/privacy") {
                UIApplication.shared.open(url)
            }
        }
        label.attributedText = attributedString
        return label
    }()
    
    
    
    lazy var loginBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 16)
        button.setTitle("登录", for: .normal)
        button.setTitle("登录", for: .selected)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.white, for: .selected)
        button.isSelected = true
        button.allRound(22)
        button.backgroundColor = Theme.color.main
        return button
    }()
    
    lazy var otherLine: UIView = {
        let view = UIView()
        view.backgroundColor = Theme.color.lineColor
        return view
    }()
    
    lazy var otherTipsLb: UILabel = {
        let label = UILabel()
        label.textColor = Theme.color.text_d4
        label.backgroundColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 12)
        label.text = "  其他方式登录  "
        return label
    }()
    
    lazy var phoneBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_login_phone 1"), for: .normal)
        button.isHidden = true
        return button
    }()
    
    lazy var appleBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_login_apple"), for: .normal)
        return button
    }()
    
    lazy var aBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_login_a"), for: .normal)
        button.isHidden = true
        return button
    }()
    
    lazy var fastLoginView: FastLoginView = {
        let view = FastLoginView()
        return view
    }()
    
    
    func startCountdown() {
        codeView.codeBtn.isEnabled = false
        remainingSeconds = 60
        updateButtonTitle()
        countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
    }

    @objc func updateCountdown() {
        remainingSeconds -= 1
        updateButtonTitle()
        
        if remainingSeconds <= 0 {
            countdownTimer?.invalidate()
            countdownTimer = nil
            codeView.codeBtn.isEnabled = true
            codeView.codeBtn.setTitle("获取验证码", for: .normal)
        }
    }

    func updateButtonTitle() {
        codeView.codeBtn.setTitle("\(remainingSeconds)秒", for: .disabled)
    }
}
//app 登录
@available(iOS 13.0, *)
extension LoginViewController:ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    func appleLogin(){
        if !self.agreeBtn.isSelected {
            NDProgressHUD.showError(title: "提示", subtitle: "请同意用户协议和隐私政策")
            return
        }
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        request.requestedScopes = [.email]
        let controller = ASAuthorizationController(authorizationRequests: [request])
        controller.delegate = self
        controller.presentationContextProvider = self
        controller.performRequests()
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            // 用户已成功登录，可以获取用户信息
            let userIdentifier = appleIDCredential.user
            //            let email = appleIDCredential.email
            //            let fullName = appleIDCredential.fullName
            let authorizationCode = String(data: appleIDCredential.authorizationCode!, encoding: String.Encoding.utf8)!
            let identityToken = String(data: appleIDCredential.identityToken!, encoding: String.Encoding.utf8)!
            self.authorizeAccount(identityToken)
            // 在这里可以处理用户信息，进行注册或登录操作
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // 处理错误情况
        print("Apple Sign-In Error: \(error.localizedDescription)")
    }
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
    
    func authorizeAccount(_ token: String) {
        NDProgressHUD.showLoading()
        RequestService.instance.appleLogin(token, completeClosure: {
            NDProgressHUD.showSuccess(title: "", subtitle: "登录成功")
        }, failureClosure: { err in
            NDProgressHUD.showError(title: "", subtitle: err ?? "")
        })
    }
}

